package com.lovo.atm.dao.impls;

import com.lovo.atm.bean.HistoryRecordBean;
import com.lovo.atm.bean.UserBean;
import com.lovo.atm.dao.IHistoryDao;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 交易记录持久化实现
 */
public class IHistoryDaoImpls extends BaseDao implements IHistoryDao {
    @Override
    public void update(HistoryRecordBean historyRecordBean) {

        this.setConnection();
        try {
            ps = con.prepareStatement(" insert into t_atmInfos(l_date,l_info,fk_username,l_money)"+"values(?,?,?,?)");
//                填充占位符
            ps.setObject(1,historyRecordBean.getDate());
            ps.setObject(2,historyRecordBean.getDescription());
            ps.setObject(3,historyRecordBean.getUser().getName());
            ps.setObject(4,historyRecordBean.getAccount());
//            更新数据库
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//                关闭链接
            this.closeConnection();
        }

    }

    @Override
    public List<HistoryRecordBean> findByCode(String code) {
        List <HistoryRecordBean>list = new ArrayList<>();

//        链接
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_atmInfos where fk_username= ?");
            ps.setObject(1,code);

//            结果集
            rs = ps.executeQuery();
            while (rs.next()) {
                HistoryRecordBean userBean = new HistoryRecordBean(rs.getString("l_info"),
                        rs.getInt("l_money"),
                                rs.getString("fk_username")
                        );
                userBean.setDate(LocalDate.parse(rs.getString("l_date")));
                list.add(userBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭
            this.closeConnection();
        }

        return list;
    }

    public static void main(String[] args) {
        IHistoryDao iHistoryDao = new IHistoryDaoImpls();
//        iHistoryDao.update(new HistoryRecordBean("转账",4000,"李四"));
//        ;
        System.out.println(iHistoryDao.findByCode("张3"));

    }
}
